/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { previewer } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';
import { useDollyCamera } from '../../../../product/commands/common/hooks/useDollyCamera';

type objDataType = pickedFaceData | pickedLineData | pickedVertexData;

type FormDataType = {
  obj: objDataType[];
  plane: pickedFaceData;
  keepSrc: boolean;
};

function SurfaceDialog({ title, onClose, props }: CurvedCmdDialogParams) {
  useDollyCamera();

  const initData = {
    obj: undefined,
    plane: undefined,
    keepSrc: true,
  };
  const { picker } = useTools();

  const [formData, setFormData] = useState<FormDataType>(initData);

  // const [obj, setObj] = useState<objDataType>(undefined);

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const obj = props?.params?.base;
      const plane = props?.params?.plane;
      const keepSrc = props?.params?.keepSrc;
      await initEditDependency([obj, plane]);
      const defaultObj = obj
        ? (picker.generatePickObjByPickID(obj) as objDataType)
        : undefined;

      const defaultPlane = plane
        ? (picker.generatePickObjByPickID(plane) as pickedFaceData)
        : undefined;
      setFormData({
        obj: [defaultObj],
        plane: defaultPlane,
        keepSrc: keepSrc,
      });
      // setObj(defaultObj);
    } else {
      setFormData(initData);
    }
  }, []);

  const excute = async (preview: boolean) => {
    const { obj, plane, keepSrc } = formData;
    const params = {
      plane: plane?.meshId,
      keepSrc: keepSrc,
    };

    if (props) {
      const res = await wsApi.setParams(props.shape, params, preview);
      if (preview) {
        previewInCommand(res);
      }
    } else {
      await confirmCommand(
        {
          a: params,
          o: obj.map((i) => getIdOfPickedObj(i)),
        },
        preview,
      );
    }
  };

  const checkAndFinishDraw = async () => {
    const { obj, plane } = formData;
    if (isEmpty(obj) || isEmpty(plane)) {
      return;
    }

    await excute(false);
    onClose();
  };

  const preview = async () => {
    const { obj, plane } = formData;
    if (props) {
      previewer.clear();
    } else {
      clear();
    }

    if (isEmpty(obj) || isEmpty(plane)) {
      clear();
      return;
    }

    await excute(true);
  };

  const isFormDataValid = () => {
    const { obj, plane, keepSrc } = formData;
    return obj?.length > 0 && plane !== null && keepSrc !== null;
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      obj: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        format: PickInputRJSFFormat.MultiPickALL,
        uniqueItems: true,
      },
      plane: {
        type: 'string',
        format: PickInputRJSFFormat.PickPlane,
      },
      keepSrc: {
        type: 'boolean',
        title: '显示初始元素',
        default: true,
      },
    },
  };

  const {
    initEditDependency,
    initingEdit,
    clear,
    confirmCommand,
    isLoading,
    previewInCommand,
  } = useCommand('cmd-mirror', {
    commandName: 'CreateMirror',
    editDxid: props?.shape,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  return (
    <PickableCommandForm
      disabled={initingEdit}
      submitLoading={isLoading}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        obj: {
          'ui:placeholder': '请输入元素',
          'ui:autofocus': true,
        },
        plane: {
          'ui:placeholder': '请输入对称面',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdCurveMirror: CurvedBaseCommand = {
  id: 'CmdMirror',
  label: 'command.mirror',
  icon: 'commands/curved/mirror',
  create: (label: string, onClose: () => void, props: any) => (
    <SurfaceDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
